#include "samplers.fx"

//_____S T R U C T U R E S_________________________________
struct FireParticle
{
	float4 position		: POSITION;
	float4 direction	: DIRECTION; 
	float4 params		: PARAMETERS;
};

struct GS_OUT
{
	float4	position	: SV_POSITION;
	float2	tex			: COORDS;
	float	alpha		: ALPHA;
};

//________________V A R I A B L E S___________________________________

float4x4 mView;
float4x4 mProj;

//________________S H A D E R S_______________________________________
FireParticle VS_DrawParticles(FireParticle vin)
{
	return vin;
}

//_________________________________________
[maxvertexcount(4)]
void GS_DrawParticles(point FireParticle gin[1], inout TriangleStream<GS_OUT> gstream)
{

	if (gin[0].params.w < 0) // no emitters rendered
	{
		float4 pos = mul(gin[0].position, mView);
		float offset = 0.1f;
		pos.z -= offset;
	
		GS_OUT quad[4];
		float size = 0.1f * gin[0].params.y;
		float4 offsets[4];
		offsets[0] = float4(-size,  size, 0, 0);
		offsets[1] = float4( size,  size, 0, 0);
		offsets[2] = float4(-size, -size, 0, 0);
		offsets[3] = float4( size, -size, 0, 0);

		float2 coords[4];
		coords[0] = float2(0,0);
		coords[1] = float2(1,0);
		coords[2] = float2(0,1);
		coords[3] = float2(1,1);

		for (int i=0; i<4; i++) {
			quad[i].position = pos + offsets[i];
			quad[i].position = mul(quad[i].position, mProj);
			quad[i].alpha = gin[0].params.y;
			quad[i].tex = coords[i];
			gstream.Append(quad[i]);
		}
	}
}

//_________________________________________

static const float3 RED = { 1, 0, 0 };
static const float3 YELLOW = { 1, 1, 0 };


Texture2D texFireParticle;

float4 PS_DrawParticles(GS_OUT pin) : SV_TARGET
{
	float4 tex = texFireParticle.Sample(s_linear, pin.tex);
	float3 color = lerp(YELLOW, RED, pin.alpha);
	
	return float4(color,min(pin.alpha, tex.w));
}




BlendState bs_transparent
{
	AlphaToCoverageEnable = false;
	BlendEnable[0] = true;
	

	SrcBlend[0] = SRC_ALPHA;
	DestBlend[0] = INV_SRC_ALPHA;
	BlendOp[0] = ADD;

	SrcBlendAlpha[0] = ONE;
	DestBlendAlpha[0] = ZERO;
	BlendOpAlpha[0] = ADD; 
};


DepthStencilState disabled
{
	DepthEnable = false;
	DepthWriteMask = false;
};




technique10 DrawParticles
{
	pass P0
	{
		SetVertexShader( CompileShader ( vs_4_0, VS_DrawParticles() ) );
		SetGeometryShader( CompileShader ( gs_4_0, GS_DrawParticles() ) );
		SetPixelShader( CompileShader ( ps_4_0, PS_DrawParticles() ) );
		
		SetDepthStencilState(disabled, 0);
		SetRasterizerState(0);
		SetBlendState(bs_transparent, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xffffffff);
	}
}

